<?php
namespace User\Controller;
use Think\Controller;
class WxController extends Controller {
	
	public static $wx;//缓存微信对象
	public static $wx_openid;//缓存微信对象
	
	public function __construct($options){
		$options['appid']=C('BB_APPID');
		$options['secret']=C('BB_SECRET');
		$options['token']=C('BB_TOKEN');
		self::$wx=new \bb\Wechat($options);
		
		//判断验证模式
		if(IS_GET){
			self::$wx->valid();
		}else{
			if(!self::$wx->valid()){die('no access!!!');}
			$data=self::$wx->request();
			//==调试信息====================================
			/*
			foreach($data as $k=>$v){
				$str=$str.$k."=>".$v.'  ';
			}
			file_put_contents('aaa.txt','收到请求:'.date('Y-m-d H:i:s').PHP_EOL.'通知信息:'.$str.PHP_EOL.PHP_EOL.PHP_EOL,FILE_APPEND);
			*/
			//==调试信息====================================
			self::$wx_openid=$data['fromusername'];
			//==和公众号有交互的时候更新用户信息=====================================================
			if($data['msgtype']!='event' || ($data['event']!='LOCATION' &&  $data['event']!='TEMPLATESENDJOBFINISH')){ //不要在更新坐标和发送模板消息的时候更新用户
				$user=M('weixin_user')->where(array('openid'=>self::$wx_openid))->find();
				if($user){
					$userdata=self::$wx->user(self::$wx_openid);
					$userdata['id']=$user['id'];
					M('weixin_user')->save($userdata);
					unset($user,$userdata);
				}
			}
			//=====================================================================
			switch($data['msgtype']){
				case 'text':
					$this->checkKeyword($data['content'],$data);
					break;
				case $data['msgtype']=='image' || $data['msgtype']=='voice' || $data['msgtype']=='video' || $data['msgtype']=='shortvideo' || $data['msgtype']=='location' || $data['msgtype']=='link':
					$this->checkKeyMedia($data);
					break;
				case 'event':
					$this->checkEvent($data);
					break;
				default:
					self::$wx->response("本系统暂时无法识别您的指令！",'text');
			}
		}
	}
	//默认页面
	public function index(){
		
		
	}
	//文本消息
	public function checkKeyword($Keyword,$request){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$message=M('weixin_message');
		$data=$m->where(array('keyword'=>$Keyword))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			$re=$message->add($request);
			if($re){
				//定时上午9点开始到晚上8点 之间通知客服回复消息
				if(date('H') >= '09' && date('H') <= '21'){
					$tp=new \bb\template();
					$array=array(
						'openid'=>self::$wx_openid,
						'zy'=>$Keyword,
						'time'=>date("Y-m-d H:i:s",time()),
					);
					$kefu=M('weixin_kefu')->order('tstime asc')->find();
					$templatedata=$tp->enddata('usertx',$kefu['openid'],$array);	//组合模板数据
					$re=self::$wx->sendTemplate($templatedata);
					if($re){
						$kefu['tstime']=time();
						M('weixin_kefu')->save($kefu);
					}
				}else{
					self::$wx->response('该时段客服已下班,明天上班后会回复您','text');
				}
			}
			self::$wx->response("no",'text');
		}
	}
		
	//事件消息
	public function checkEvent($data){
		switch($data['event']){
			//关注
			case 'subscribe':
				if($data['eventkey']){
					//扫码关注
					$this->checksmsubscribe($data['eventkey'],$data['ticket']);
				}else{
					//关注
					$this->checksubscribe();
				}
				break;
			//取消关注
			case 'unsubscribe':
				$this->checkunsubscribe();
				break;
			//关注后扫码
			case 'SCAN':
				$this->checkscan($data['eventkey'],$data['ticket']);
				break;
			//上报用户地理位置
			case 'LOCATION':
				$this->checklocation($data['latitude'],$data['longitude'],$data['precision']);
				break;
			//自定义菜单事件命令
			case 'CLICK':
				$this->checkCLICK($data['eventkey']);
				break;
			//自定义菜单事件打开网页
			case 'VIEW':
				$this->checkVIEW($data['eventkey']);
				break;
			default:
				self::$wx->response("本系统暂时无法识别你的事件 ！",'text');
		}
	}
	//关注公众号
	public function checksubscribe(){
		$m=M('weixin_user');
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
		//==获得需要 获动结束就取消===============================================================
//		$array[0]['title']='迎中秋，庆国庆 ▍猜_boss☞赢月饼&电影票&红酒&红包';
//		$array[0]['description']='文中大咖都是中国商界的顶级精英；双节来了，各位大佬一定动作频频！！“我要洗衣” app随时全面上线之前，决定做个小小活动抛砖引玉！哈哈~作为一个爱学习，爱创新的互联网O2O干洗团队，决定吸取各位大咖优点，以此来造福广大用户！';
//		$array[0]['picurl']='http://wx.iwantwash.com/Public/h/img/cboss.png';
//		$array[0]['url']='http://mp.weixin.qq.com/s?__biz=MzAxOTE2Mjk3OQ==&mid=208319680&idx=1&sn=997c2fac71af589add7596c6678cf65c&scene=23&srcid=09197TFjxSX73NcgXQkJilEh#rd';
//		$array[1]['title']='疯狂数钱赢红包！敢不敢来挑战？';
//		$array[1]['description']='一阳指？点穴手？听说数钱会上瘾？点钞赢微信现金红包，不服来战!';
//		$array[1]['picurl']='http://wx.iwantwash.com/Public/h/img/fx.jpg';
//		$array[1]['url']='http://wx.iwantwash.com/H/sq/index/id/1';
//		self::$wx->sendMsg(self::$wx_openid,$array,'news');
		//================================================================
		$keym=M('weixin_keyword');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
		
		self::$wx->response("感谢您的关注！".$data['id'],'text');
	}
	
	//扫描2微码关注公众号
	public function checksmsubscribe($eventkey,$ticket){
		$m=M('weixin_user');
		$userdata=self::$wx->user(self::$wx_openid);
		$m->add($userdata);
		$keym=M('weixin_keyword');
		$data=$keym->where(array('keyword'=>"首次关注"))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("?",'text');
		}
	}
	
	//关注过扫码
	public function checkscan($eventkey,$ticket){
		$m=M('weixin_user');
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$userdata=self::$wx->user(self::$wx_openid);
			$userdata['id']=$user['id'];
			$m->save($userdata);
		}else{
			$userdata=self::$wx->user(self::$wx_openid);
			$m->add($userdata);
		}
	}
	
	//自定义菜单事件命令
	public function checkCLICK($eventkey){
		$m=M('weixin_keyword');
		$news=M('weixin_news');
		$message=M('weixin_message');
		$data=$m->where(array('keyword'=>$eventkey))->find();
		if($data){
			if($data['type']=='text'){
				self::$wx->response($data['content'],'text');
			}elseif($data['type']=='news'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}elseif($data['type']=='newss'){
				$news=$news->where(array('kid'=>$data['id']))->select();
				$news=$this->newsbl($news);
				self::$wx->response($news,'news');
			}
		}else{
			self::$wx->response("no",'text');
		}
		
	}
	
	//自定义菜单事件打开网页
	public function checkVIEW($eventkey){
		//微信会打开这个网址$eventkey
	}
	
	//用户地理位置
	public function checklocation($latitude,$longitude,$precision){
		$m=M('weixin_user');
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		if($user){
			$url = "http://api.map.baidu.com/geoconv/v1/?coords=".$longitude.",".$latitude."&from=1&to=5&ak=".C('BB_AK');
	 		$re = get_curl($url);
			$zb = json_decode($re,true);
			if($zb['status']==0){
				$userdata['longitude']=$zb['result']['0']['x'];
				$userdata['latitude']=$zb['result']['0']['y'];
				$userdata['id']=$user['id'];
				$m->save($userdata);		//更新用户位置坐标。
				//self::$wx->response('坐标更新了！','text');
			}else{
				//self::$wx->response($zb['status'],'text');
				//self::$wx->sendMsg('oY8X0s9aYANqYI3ETXPnlKYcDS4o',$zb['status'],'text');
			}
		}
	}
	
	//==多媒体资料处理=======================================================
	public function checkKeyMedia($data){
		$message=M('weixin_message');
		switch($data['msgtype']){
			//用户发来照片
			case 'image':
				$path=self::$wx->download_medis($data['mediaid']);	//下载图片到本地
				$data['content']=$path;
				break;
			//用户发来语音
			case 'voice':
				$data['content']=$data['recongnition'];				//语音识别结果
				break;
			//用户发来视频
			case 'video':
				//暂不处理
				break;
			//用户发来小视频
			case 'shortvideo':
				//暂不处理
				break;
			//用户发来地理位置
			case 'location':
				//暂不处理
				break;
			//用户发来链接
			case 'link':
				//暂不处理
				break;
			default:
				self::$wx->response("本系统暂时无法识别您的指令！",'text');
		}
        $re=$message->add($data);
		if($re){
			//定时上午9点开始到晚上8点 之间通知客服回复消息
			if(date('H') >= '09' && date('H') <= '21'){
				$tp=new \bb\template();
				$array=array(
					'openid'=>self::$wx_openid,
					'zy'=>$Keyword,
					'time'=>date("Y-m-d H:i:s",time())
				);
				$kefu=M('weixin_kefu')->order('tstime asc')->find();
				$templatedata=$tp->enddata('usertx',$kefu['openid'],$array);	//组合模板数据
				$re=self::$wx->sendTemplate($templatedata);
				if($re){
					$kefu['tstime']=time();
					M('weixin_kefu')->save($kefu);
				}
			}else{
				self::$wx->response('该时段客服已下班,明天上班后会回复您','text');
			}
			self::$wx->response("no",'text');
		}else{
			self::$wx->response('没有收到您发送的数据，请重试！','text');
		}
	}
	//取消关注公众号
	public function checkunsubscribe(){
		$m=M('weixin_user');
		$user=$m->where(array('openid'=>self::$wx_openid))->find();
		$m->delete($user['id']);		//删除取消关注的会员
	}
	
	//遍历微信图文回复数据
	public function newsbl($data){
		foreach ($data as $k => $v) {
			$img=$this->getPic($v['img']);
			$array[$k]['Title']=$v['title'];
			$array[$k]['Description']=$v['info'];
			$array[$k]['PicUrl']=$img['imgurl'];
			$array[$k]['Url']=htmlspecialchars_decode($v['url']);
		}
		return $array;
	}
	//获取单张图片地址
	public function getPic($id){
		$m=M('weixin_upload_img');
		$map['id']=$id;
		$list=$m->where($map)->find();
		if($list){
			$list['imgurl']=C('BB_URL')."/Upload/".$list['savepath'].$list['savename'];
		}
		return $list?$list:"";
	}
}